package com.duapk.web.servlet;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.duapk.common.Result;
import com.duapk.common.SearchResult;
import com.duapk.web.conf.SystemConfig;
import com.duapk.web.log.LogManager;
import com.duapk.web.util.DateUtil;
import com.duapk.web.util.HttpUtils;
import com.duapk.web.util.JSONUtils;

/**
 * 搜索入口
 * 
 * @author yangfeng
 * 
 */
public class SearchServlet extends HttpServlet {

	// 日志对象
	private static Logger logger = LoggerFactory.getLogger(SearchServlet.class);

	private static final long serialVersionUID = 3301400331735599048L;

	/**
	 * 注意中文问题:需要在server.xml 的 Connector 中增加 URIEncoding="gbk"
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//处理中文
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		String queryString = request.getQueryString();
		// 数据不合法，转向首页
		if (queryString == null || queryString.trim().length()<30) {
			request.getRequestDispatcher("/index.htm").forward(request,
					response);
			return;
		}

		// 获取相关参数
		String q = request.getParameter("q");// 搜索关键字
		q = q.trim();
		String p = request.getParameter("p");// 分页索引
		String s = request.getParameter("s");
		int pageID = 1;
		int pageSize = 10;
		try {
			pageID = Integer.parseInt(p);
			pageSize = Integer.parseInt(s);
		} catch (Exception e) {
			logger.error("Parameter error!",e);
		}

		// 获取搜索结果

		StringBuilder searchSB = new StringBuilder("q=");
		searchSB.append(q).append('&').append(queryString);
		SearchResult searchResult = search(searchSB.toString());
		
		if (searchResult == null) {
			searchResult = new SearchResult();
		} else {
			doResultAction(searchResult);
		}
		// 获取搜索参数
		searchResult.setKeyword(q);
		searchResult.setPageID(pageID);
		
		StringBuilder sb = new StringBuilder();
		sb.append("q=").append(q).append('&');
		sb.append("v=").append(request.getParameter("v")).append('&');
		sb.append("star=").append(request.getParameter("star")).append('&');
		sb.append("size=").append(request.getParameter("size")).append('&');
		sb.append("f=").append(request.getParameter("f")).append('&');
		sb.append("pubtime=").append(request.getParameter("pubtime"))
				.append('&');
		sb.append("s=").append(pageSize).append('&');
		sb.append("t=").append(request.getParameter("t"));
		String parameters = sb.toString();
		searchResult.setParameters(parameters);

		// 计算分页
		int totalItem = searchResult.getTotalItem();
		// 结果只有一页
		if (totalItem > pageSize) {
			// 计算总共的分页数
			int pagintions = totalItem / pageSize;
			if (pagintions * pageSize < totalItem) {
				pagintions++;
			}
			searchResult.setPos(pageID);
			if (pageID + 9 > pagintions) {
				searchResult.setEnd(pagintions);
			} else {
				searchResult.setEnd(pageID + 9);
			}
			if (pageID < pagintions) {
				searchResult.setShowNextLink(true);
			}
		}

		// 展示上一页链接
		if (pageID > 1) {
			searchResult.setShowUpLink(true);
		}
		
		request.setAttribute("result", searchResult);
		request.getRequestDispatcher("/WEB-INF/jsp/result.jsp").forward(
				request, response);
		
		//记录搜索日志
		LogManager.searchLog("WWW", q, request.getParameter("t"), request.getParameter("v"),
					pageID, searchResult.getTotalItem(), request.getRemoteAddr(), request.getHeader("User-Agent"));
		return;
	}

	/**
	 * 处理搜索结果
	 * 
	 * @param searchResult
	 * @throws UnsupportedEncodingException
	 */
	private void doResultAction(SearchResult searchResult)
			throws UnsupportedEncodingException {
		List<Result> list = searchResult.getResultList();
		// 处理对应的链接地址
		if (list != null) {
			for (Result result : list) {
				// 处理访问URL
				handResult(result);
				//处理相同结果
				Result nextResult = result.getNextResult();
				if(nextResult!=null){
					while(true){
						handResult(nextResult);
						nextResult = nextResult.getNextResult();
						if(nextResult==null){
							break;
						}
					}
				}
			}
		}
	}
	
	/**
	 * 对每个结果进行预处理
	 * @param result
	 * @throws UnsupportedEncodingException
	 */
	protected void handResult(Result result)
			throws UnsupportedEncodingException {
		String url = result.getDetailUrl();
		url = URLEncoder.encode(url, HttpUtils.UTF_HTTP_ENCODING);
		String title = result.getTitle();
		title = URLEncoder.encode(title, HttpUtils.UTF_HTTP_ENCODING);
		result.setProxyDetailUrl("/v?u=" + url + "&n=" + title);
		
		//处理下载URL
		url = result.getDownloadUrl();
		url = URLEncoder.encode(url, HttpUtils.UTF_HTTP_ENCODING);
		result.setDownloadUrl("http://www.duapk.com/d?u=" + url + "&n=" + title);
		
		String detailUrl = result.getDetailUrl();
		if (detailUrl.startsWith("http://")) {
			result.setDetailUrl(detailUrl.substring(7));
		}

		// 处理发布时间
		long putTime = result.getPubtime();
		Date date = new Date(putTime);
		result.setPubTimeStr(DateUtil.dateToString(date,
				DateUtil.FILE_DATE_FORMAT));
		// 处理文件大小
		long size = result.getSize();
		float ksize = size / 1024f;
		if (ksize >= 1024) {
			result.setFileSizeStr(round(ksize / 1024f) + "M");
		} else {
			result.setFileSizeStr(round(ksize) + "K");
		}
		// 处理星级
		String start = result.getStar();
		float temp = Float.parseFloat(start);
		result.setStarInt((int) temp);
	}

	/**
	 * 四舍五入处理
	 * @param number
	 * @return
	 */
	private float round(float number) {
		int b = Math.round(number * 100); // 小数点后两位前移，并四舍五入
		float c = (float) b / 100f; // 还原小数点后两位
		return c;
	}

	private static final String searchEngineUrl = SystemConfig
			.getConfigString("engine.url");

	/**
	 * 将用户搜索信息提交给搜索引擎处理
	 * 
	 * @param queryString
	 * @return
	 */
	private SearchResult search(String queryString) {
		String content = HttpUtils.sentPost(searchEngineUrl, queryString);
		SearchResult result = null;
		try {
			result = JSONUtils.fromJson(content, SearchResult.class);
		} catch (Exception e) {
			logger.error("Get Search Result Error! queryString={}",
					queryString, e);
		}
		return result;
	}
}
